import { listen } from '@src/utils/listener'
import __util from "@src/events/__util";

export function onWindowMousedown(ev, self, option) {
  option.down = true
  option.downX = option.lastX = ev.clientX
  option.downY = option.lastY = ev.clientY
  self.cameraVelocity.multiplyScalar(0)
  option.clickActive = true

  console.log(ev, self, option)
  if (ev.preventDefault) {
    ev.preventDefault()
  }
}

export function onOverlaysMousemove (ev, self) {
  self.mouseCurrent.clientX = ev.clientX
  self.mouseCurrent.clientY = ev.clientY
}

export function onWindowMousemove (ev, self, option) {
  const { $scope, $overlays, $camera, $gl } = self
  let { introLength, introTime, cameraY, cameraZMotion, cameraZTarget } = $camera

  if (option.down) {
    var dy = ev.clientY - option.lastY
    var dx = ev.clientX - option.lastX
    self.cameraVelocity.z = (
      self.touchMode
        ? self.cameraVelocity.z / 2 + (-dy / 3) / 2
        : self.cameraVelocity.z / 2 + -dy
    );

    option.lastY = ev.clientY
    option.lastX = ev.clientX

    if (Math.abs(option.downY - option.lastY) > 5 || Math.abs(option.downX - option.lastX) > 5) {
      option.clickActive = false
    }

    if (self.touchMode) {
      self.cameraVelocity.x = self.cameraVelocity.x/2 + (-4*dx / $gl.width)/2;
      if (dx*dx > dy*dy) {
        self.cameraVelocity.z = 0
      } else {
        self.cameraVelocity.x = 0
      }
      if (cameraXOffset > 1) {
        self.$camera.cameraXOffset = 1
        self.cameraVelocity.x = 0
      }
      if (cameraXOffset < -1) {
        self.$camera.cameraXOffset = -1
        self.cameraVelocity.x = 0
      }
    }

  } else if (ev.target === $overlays) {
    var previousHovered = null

    self.$objects.blobs.children.forEach(function(c) {
      if (c.hovered) {
        previousHovered = c
      }
      c.hovered = false
    });

    var obj = __util.findToolbarUnderEvent(ev, self)

    if (obj) {
      $scope.hoveredGeography = obj.geographyName
    } else {
      $scope.hoveredGeography = null
      obj = __util.findObjectUnderEvent(ev, self)
      if (obj) {
        obj.hovered = true
        if (obj !== previousHovered && (obj.soundLastPlayed == null || (Date.now() - obj.soundLastPlayed) > 200)) {
          obj.soundLastPlayed = Date.now()
          if (obj.soundIndex === undefined) {
            obj.soundIndex = -4 * obj.position.y
          }
          // self.audioManager.playSoundEffect(obj.soundIndex);
        }
      }
    }
  }

  var mouse3D = new THREE.Vector3(
    ( ev.clientX / $gl.width ) * 2 - 1,
    -( ev.clientY / $gl.height ) * 2 + 1,
    0.5
  )

  if (introTime > introLength) {
    self.$camera.cameraXOffset = self.touchMode ? cameraXOffset : mouse3D.x
    self.$camera.cameraYOffset = self.touchMode ? ($gl.width > $gl.height ? 1 : 0.5) : mouse3D.y
  }

  if (ev.preventDefault) {
    ev.preventDefault()
  }
}

export function onWindowMouseup (ev, self, option) {
  const { $scope, $overlays, $gl } = self
  option.down = false
  self.$camera.cameraZMotion = 0
  self.$camera.cameraZTarget = null
  if (ev.preventDefault) {
    ev.preventDefault()
  }

  if (option.clickActive && ev.target === document.getElementById('overlays')) {
    var obj = __util.findToolbarUnderEvent(ev, self)


    if (obj) {
      if ($scope.selectedGeography === obj.geographyName) {
        $scope.selectedGeography = null
      } else {
        $scope.selectedGeography = obj.geographyName
      }
    } else {
      var obj = __util.findObjectUnderEvent(ev, self)
      var catchObj = self.findObjectUnderEvent(ev);
      var bullet = '';


      self.$objects.blobs.children.forEach(function(c) {
        c.selected = false
        c.connectionSelected = false
        if (obj && !bullet) {
          bullet = obj.objectData.relatedNodes ? obj.objectData.relatedNodes[0] : ''
        }
        if (bullet && bullet === item.objectData.bullet) {
          obj = item
        }
      });

      console.log('clickActive', obj, self.$objects.blobs.children);

      var needDigest = false

      if (obj) {
        obj.selected = true
        if (!$scope.categoryToggled && $scope.category !== obj.objectData.categoryName) {
          $scope.category = (obj.objectData.categoryName + '').toLowerCase()
          $scope.__bullet = catchObj.objectData.bullet;
          needDigest = true
        }

        obj.connections.forEach(function(c) {
          c.connectionSelected = true
        });

      } else if (!$scope.categoryToggled && $scope.category !== null) {
        $scope.category = null
        $scope.__bullet = null;
        needDigest = true
      }

      var hoverInfoEl = document.getElementById('object-hover-info');
      var hoverTitleEl = document.getElementsByClassName('object-hover-title')[0];
      var hoverCultureEl = document.getElementsByClassName('object-hover-culture')[0];
      var hoverPersonEl = document.getElementsByClassName('object-hover-person')[0];

      if ($scope.hoverInfoObject !== obj) {
        $scope.hoverInfoObject = obj
        needDigest = true
        if (needDigest) {
          // 出发脏值检查
          // $scope.$digest();
        }
        // console.log(obj)
        if ($scope.hoverInfoObject) {
          /// width
          if (ev.clientX + 480 > $gl.width && ev.clientX - 480 < 0) {
            hoverInfoEl.style.left = $gl.halfX - 460/2 + 'px'
            hoverInfoEl.style.right = 'auto'
          } else if (ev.clientX + 460 > $gl.width) {
            hoverInfoEl.style.right = $gl.width - (ev.clientX - 50) + 'px'
            hoverInfoEl.style.left = 'auto'
          } else {
            hoverInfoEl.style.right = 'auto'
            hoverInfoEl.style.left = ev.clientX + 50 + 'px'
          }

          /// height
          if (ev.clientY + 200 > $gl.height) {
            hoverInfoEl.style.top = 'auto'
            hoverInfoEl.style.bottom = $gl.height - (ev.clientY - 30) + 'px'
          } else {
            hoverInfoEl.style.bottom = 'auto'
            hoverInfoEl.style.top = ev.clientY + 30 + 'px'
          }

          hoverTitleEl.innerText = obj.objectData.title
          hoverCultureEl.innerText = obj.objectData.description

          /*if (obj.objectData.personnel) {
            var persons = obj.objectData.personnel.map(item => {
              return `<div class="object-hover-person-item">${ item || '空' }</div>`
            }).join('')
            hoverPersonEl.innerHTML = `参会人员: ${ persons }`
          }*/

          hoverInfoEl.style.backgroundColor = $scope.hoverInfoObject.objectData.backgroundColor
          hoverInfoEl.setAttribute('class', 'visible')
        } else {
          hoverInfoEl.setAttribute('class', '')
        }
        // self.render();
      } else if (obj && $scope.hoverInfoObject === obj) {
        self.$objects.blobs.children.forEach(function(c) {
          c.selected = false
          c.connectionSelected = false
        })
      } else {
        $scope.selectedGeography = null
      }
    }
  }
}

export function onOverlaysMousewheel (ev, self) {
  const { $scope, $camera, camera } = self
  if ($scope.introState < 4) {
    if (ev.wheelDelta < 0) {
      // self.render()
      // $scope.$digest()
    }
  } else if ($camera.introTime >= $camera.introLength + 16) {
    self.$camera.cameraZTarget = (
      $camera.cameraZTarget || camera.position.z
    ) - ev.wheelDelta * 0.15
  }
}

export function setupMouseEvent (self, option) {
  const { $scope, $overlays } = self

  listen(window, 'mousedown', function(ev) {
    onWindowMousedown(ev, self, option)
  })

  listen($overlays, 'mousemove', function(ev) {
    onOverlaysMousemove(ev, self)
  })

  listen(window, 'mousemove', function(ev) {
    onWindowMousemove(ev, self, option)
  })

  /**
   * 鼠标按钮松开事件
   * @param ev
   */
  listen(window, 'mouseup', function(ev) {
    onWindowMouseup(ev, self, option)
  })

  /**
   * 鼠标滚轮滚动事件
   * @param ev
   */

  listen(window, 'mousewheel', function(ev) {
    onOverlaysMousewheel(ev, self, option)
  })
}
